import pymysql
from sqlalchemy import JSON

from app import db
from app.models import Book
from app.models import User
from app.models import Borrow
from flask import Blueprint, render_template, request, redirect, url_for
import json

bp = Blueprint('AllBooks', __name__, url_prefix='/user')

# Json序列化
import decimal

import cv2
from pyzbar import pyzbar


def scan_qrcode(qrcode):
    data = pyzbar.decode(qrcode)
    return data[0].data.decode('utf-8')


class DecimalEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        super(DecimalEncoder, self).default(o)


@bp.route('/AllBooks', methods=['GET', 'POST'])
def AllBooks():
    book = Book.query.all()
    context = {
        'books': book
    }
    return render_template('AllBooks.html', **context)


@bp.route('/qecode', methods=['GET', 'POST'])
def qecode():
    cap = cv2.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        cv2.imshow('scan qrcode', frame)

        # 解析二维码
        text = None
        try:
            text = scan_qrcode(frame)
        except Exception as e:
            pass
        if text:
            print(text)
            break

        key = cv2.waitKey(10)
        if key == ord('q'):
            break
    cv2.destroyAllWindows()
    # res = text[1:-1]
    # res=res.replace('\'','\"')
    # print(res)
    return json.loads(text)


@bp.route('/delete', methods=['GET', 'POST'])
def delete():
    bid = request.form['name']
    example = Book.query.get(bid)
    print(example)
    db.session.delete(example)
    db.session.commit()
    books = Book.query.all()
    print(books)
    bookLists = [book.to_dict() for book in books]
    print(bookLists)
    return json.dumps(bookLists, cls=DecimalEncoder)


@bp.route('/modify', methods=['GET', 'POST'])
def modify():
    bid = request.form['id']
    print(bid)
    books = Book.query.filter_by(bid=int(bid)).all()
    print(books)
    bookLists = [book.to_dict() for book in books]
    print(bookLists)
    return json.dumps(bookLists, cls=DecimalEncoder)


@bp.route('/returnBook', methods=['GET', 'POST'])
def returnBook():
    books = Book.query.all()
    users = User.query.all()
    borrowers = Borrow.query.all()

    bookLists = [book.to_dict() for book in books]
    userLists = [user.to_dict() for user in users]
    borrowerLists = [borrower.to_dict() for borrower in borrowers]

    return json.dumps(bookLists, cls=DecimalEncoder)


@bp.route('/modifyResult', methods=['PUT'])
def modifyResult():

    bid = request.form['bid']
    bname = request.form['bname']
    category1 = request.form['category1']
    category2 = request.form['category2']
    description = request.form['description']
    isLoaned = request.form['isLoaned']
    times = request.form['times']
    content = request.form['content']
    print(content)
    price = request.form['price']
    print(price)
    score = request.form['score']
    author = request.form['author']
    pubUnit = request.form['pubUnit']



    book = Book(bid=bid, bname=bname, category1=category1, category2=category2, description=description,
                isLoaned=isLoaned, times=times,
                content=content, price=price, score=score, author=author, pubUnit=pubUnit)

    example = Book.query.get(int(bid))
    db.session.delete(example)
    db.session.add(book)
    db.session.commit()

    books = Book.query.all()
    print(books)
    bookLists = [book.to_dict() for book in books]
    print(bookLists)
    return json.dumps(bookLists, cls=DecimalEncoder)


@bp.route('/search', methods=['GET', 'POST'])
def search():
    search = request.args.get('search')
    example = Book.query.filter_by(bid=int(search))
    context = {
        'books': example
    }
    return render_template('AllBooks.html', **context)


@bp.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('addall.html')
    else:
        bid = request.form['bid']
        bname = request.form['bname']
        category1 = request.form['category1']
        category2 = request.form['category2']
        description = request.form['description']
        # isLoaned = request.form['isLoaned']
        # times = request.form['times']
        content = request.form['content']
        cover = request.form['cover']
        price = eval(request.form['price'])
        score = request.form['score']
        author = request.form['author']
        pubUnit = request.form['pubUnit']

        book = Book(bid=bid, bname=bname, category1=category1, category2=category2, description=description,
                    isLoaned='no', times=0,
                    content=content, cover=cover, price=price, score=score, author=author, pubUnit=pubUnit)

        db.session.add(book)
        db.session.commit()

    return redirect(url_for('AllBooks.AllBooks'))


@bp.route('/base64', methods=['POST'])
def transformBase64():
    cover = request.form['base64']
    bid = request.form['bid']
    book = Book.query.filter_by(bid=bid).first()
    book.cover = cover
    db.session.add(book)
    db.session.commit()
    return ''


@bp.route('/basee')
def basss():
    return render_template('base64.html')
